<?php
/**
 * Created by PhpStorm.
 * User: wangjie
 * Date: 2020/07/27
 * Time: 下午5:13
 */
namespace App\Api\Controllers\Linkage;


use App\Api\Controllers\BaseController;
use App\Api\Controllers\Config\TfConfigController;
use App\Common\PaySuccessAction;
use App\Common\RefundSuccessAction;
use App\Models\HkrtStore;
use App\Models\LinkageStore;
use App\Models\MerchantWalletDetail;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\RefundOrder;
use App\Models\Store;
use App\Models\StorePayWay;
use App\Models\TfStore;
use App\Models\UserRate;
use App\Models\UserWalletDetail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use MyBank\Tools;

class NotifyController extends BaseController
{

    //联动优势 支付 回调（最多通知商户4次，每次间隔1分钟）
    public function pay_notify_url(Request $request)
    {
        try {
            $data = $request->all();
            
            // file_put_contents('1109.log', var_export($data, true) . "\r\n", FILE_APPEND);
            
//            $data = array (
//                'orderType' => 'wechat', //C，订单类型，alipay–支付宝；wechat–微信支付；unionpay–银联二维码；mobilepos-手机pos
//                'orderNo' => 'wx_scan20200819175705180347602', //商户订单号
//                'merPriv' => NULL, //C，商户私有域
//                'payTime' => '20200819175722', //C，交易支付时间，yyyyMMddHHmmss
//                'cardType' => NULL, //C，银行卡类型，01–借记卡；02–贷记卡
//                'sign' => 'vnL3ZgxaViTEZFrcWMd53DgwyQOT8UsSUJEkdScGKIP%2FwyjyssF%2B8PZFUDR%2BF93eSA5yXrDoN%2BEf0ZR77NEyQ88qm%2FfC%2BMatjHkcPDP4Bgt5Jv4gEJnuAd11Eto0O0C5GCGgEIg%2F8%2Fdaj%2FA9NXDfrSFMgUvrojB8C%2BGyMSC%2FFkg%3D', //C，签名
//                'acqSpId' => 'Y771350872', //代理商编号(联动平台分配)
//                'payAmt' => '1', //C，买家付款金额，单位（分）
//                'transactionId' => '00000000000000000000111979625580', //C，第三方支付订单号，联动支付流水号（条形码）
//                'notifyType' => '1', //C，通知类型，1–消费；2–撤销；3–退款
//                'payerInfo' => '%7B%22bankType%22%3A%22OTHERS%22%2C%22openid%22%3A%22oEufkwIFGHshkU8CCNIqNLGG4FfY%22%7D', //C，付款方信息
//                'acqMerId' => '42796577', //商户号(联动平台分配)
//                'currencyCode' => 'CNY', //C，交易币种 (CNY：人民币)
//                'txnAmt' => '1', //订单金额，单位（分）
//                'transIndex' => '2020081917570006353196',
////                'transIndex' => '', //C，交易索引
////                'settlementAmt' => '', //C，应结订单金额，单位（分）
////                'couponInfo' => '', //C，优惠信息
////                'dctGoodsInfo' => '', //C，单品优惠信息
////                'bankType' => '', //C，付款银行
//            );
            if ($data['pay_status'] == '1') { //1–消费
                if (isset($data['trade_no']) || isset($data['out_trade_no'])) {
                    $trade_no = $data['trade_no'];
                    $out_trade_no = $data['out_trade_no'];
      
                    $order = Order::where('out_trade_no', $out_trade_no)->first();
                    if (!$order) $order = Order::where('trade_no', $trade_no)->first();
                    // print_r($data);die;

                    //订单存在并等待支付
                    if ($order && ($order->pay_status == '2')) {
//                        if (isset($data['attach']) && !empty($data['attach'])) {
//                            $return_attach = json_decode($data['attach'], true);
//                            if ($return_attach['msg'] == 'Success') {
//                                $pay_time = $return_attach['gmt_payment']; //
//                                $buyer_user_id = $return_attach['buyer_user_id']; //
//                                $buyer_pay_amount = $return_attach['buyer_pay_amount']; //
//                                $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
//                            }
//                            if (($data['card_type'] == 'OTHERS') && ($return_attach['result_code'] == 'SUCCESS')) {
//                                $pay_time = $data['trade_channel_end_time'];
//                                $buyer_user_id = $return_attach['openid'];
//                                $other_no = $return_attach['out_trade_no'];
//                            }
//                        }

                        $buyer_pay_amount = $order['total_amount']; //订单总金额，单位（分）
                        $in_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'trade_no' => $trade_no,
                            'buyer_pay_amount' => $buyer_pay_amount,
                        ];
                        if(isset($pay_time) && !empty($pay_time)) $in_data['pay_time'] = date('Y-m-d H:i:s', strtotime($pay_time));
                        if(isset($buyer_user_id) && !empty($buyer_user_id)) $in_data['buyer_id'] = $buyer_user_id;
                        if(isset($buyer_pay_amount) && !empty($buyer_pay_amount)) $in_data['buyer_pay_amount'] = $buyer_pay_amount;
                        if(isset($other_no) && !empty($other_no)) $in_data['other_no'] = $other_no;
                        $this->update_day_order($in_data, $out_trade_no);

                        if (strpos($out_trade_no, 'scan')) {

                        } else {
                            //支付成功后的动作
                            $sucData = [
                                'ways_type' => $order->ways_type,
                                'company' => $order->company,
                                'ways_type_desc' => $order->ways_type_desc,
                                'source_type' => '5000', //返佣来源
                                'source_desc' => '联动优势', //返佣来源说明
                                'total_amount' => $order->total_amount,
                                'out_trade_no' => $order->out_trade_no,
                                'other_no' => $order->other_no,
                                'rate' => $order->rate,
                                'fee_amount' => $order->fee_amount,
                                'merchant_id' => $order->merchant_id,
                                'store_id' => $order->store_id,
                                'user_id' => $order->user_id,
                                'config_id' => $order->config_id,
                                'store_name' => $order->store_name,
                                'ways_source' => $order->ways_source,
                                'device_id' => $order->device_id
                            ];
                            if(isset($pay_time) && !empty($pay_time)) $sucData['pay_time'] = $pay_time;
                            PaySuccessAction::action($sucData);
                        }
                    }
                }
            } else { //2–撤销；3–退款
                if (isset($data['trade_no']) || isset($data['out_trade_no'])) {
                    $trade_no = $data['trade_no'];
                    $out_trade_no = $data['out_trade_no'];

                    $day = date('Ymd', time());
                    $table = 'orders_' . $day;
                    if (Schema::hasTable($table)) {
                        $order = DB::table($table)->where('out_trade_no', $out_trade_no)->first();
                        if (!$order) $order = DB::table($table)->where('trade_no', $trade_no)->first();
                    } else {
                        $order = Order::where('out_trade_no', $out_trade_no)->first();
                        if (!$order) $order = Order::where('trade_no', $trade_no)->first();
                    }

                    //订单存在并成功
                    if ($order && ($order->pay_status == '1')) {
                        $refund_amount = isset($data['payAmt'])?($data['payAmt']/100):0;
                        $transactionId = $data['transactionId'];
                        $insert_data = [
                            'status' => '6',
                            'pay_status' => 6,
                            'pay_status_desc' => '已退款',
                            'refund_amount' => $order->refund_amount + $refund_amount,
                            'fee_amount' => 0,
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        RefundOrder::create([
                            'ways_source' => $order->ways_source,
                            'type' => 5000,
                            'refund_amount' => $refund_amount, //退款金额
                            'refund_no' => $data['transactionId'], //联动流水号
                            'store_id' => $order->store_id,
                            'merchant_id' => $order->merchant_id,
                            'out_trade_no' => $out_trade_no,
                            'trade_no' => $trade_no
                        ]);
                        //退款成功后的操作
                        RefundSuccessAction::action([
                            'out_trade_no'=>$out_trade_no,
                            'refund_no' => $data['transactionId'], //联动流水号
                        ]);
                        //返佣去掉
                        UserWalletDetail::where('out_trade_no', $out_trade_no)->update([
                            'settlement' => '03',
                            'settlement_desc' => '退款订单',
                        ]);
                        MerchantWalletDetail::where('out_trade_no', $out_trade_no)->update([
                                'settlement' => '03',
                                'settlement_desc' => '退款订单',
                            ]);
                    }
                }
            }

            return json_encode([
               'respCode' => '00', //返回码（00：收到通知；其他：继续重复通知）
               'respMsg' => '收到', //返回信息
               'signature' => $data['sign'] ?? '' //签名
            ]);
        } catch (\Exception $ex) {
            Log::info('联动支付回调-error');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }
    }


    //联动优势 商户入网审核结果通知 回调 （联动优势最多通知商户4次，每次间隔1分钟）
    public function merchant_apply_notify_url(Request $request)
    {
        try {
            $data = $request->all();
            Log::info('联动优势-商户入网审核结果通知-回调原始数据');
            Log::info($data);
//            $data = {
//                'acqSpId': '', //代理商编号(联动平台分配)
//                'acqMerId': '', //商户号(联动平台分配)
//                'merId': '', //报备编号
//                'retCode': '', //审核结果通知码（0000：审核成功；0001：审核驳回）
//                'retMsg': '' //审核结果消息
//            };

            $store_info = Store::where()->first();
            if (!$store_info) {
                Log::info('联动优势-商户入网申请-回调-门店不存在');
            }

            $linkage_store = LinkageStore::where()->first();
            if ($linkage_store->status != '1') {
                $linkage_store->update([
                    'merch_no' => '',
                    'status' => '1',
                ]);
                $linkage_store->save();
            }

            return json_encode([
                'acqMerId' => '', //商户号(联动平台分配)
                'respCode' => '0000', //0000：收到通知；其他：继续重复通知
                'respMsg' => '收到审核通知', //返回信息
                'signature' => '' //签名
            ]);
        } catch (\Exception $exception) {
            Log::info('联动优势-商户入网申请-回调异步报错');
            Log::info($exception->getMessage());
        }
    }


}
